<template>
  <div>
    <div class="top-panel__box">
      <el-form :model="dataForm" ref="dataForm" inline size="small" onsubmit="return false">
        <el-row>
          <el-col :span="5">
            <el-form-item label="产品类型" label-width="80px">
              <el-select placeholder="产品类型" v-model="dataForm.productNoList" multiple clearable collapse-tags>
                <el-option v-for="(value, key) in dicts['product_type'].childMap" :key="key" :label="value" :value="key" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item>
              <el-input placeholder="输入借款编号/姓名" v-model="dataForm.freeCondition" maxlength="30" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item>
              <el-input placeholder="受理人" v-model="dataForm.acceptorName" maxlength="30" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="">
              <organization-cascader v-model="dataForm.acceptorOrgNo" :placeholder="'请选择进件受理机构'"></organization-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item>
              <el-input placeholder="逾期跟进人" v-model="dataForm.followAcceptorName" maxlength="30" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="">
              <organization-cascader v-model="dataForm.followAcceptorOrgNo" :placeholder="'逾期跟进机构'"></organization-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin:10px 0 0 80px;">
          <el-col :span="6">
            <el-form-item>
              <el-input placeholder="逾期天数最小值" v-model="dataForm.minOverdueDays" maxlength="30" style="width: 160px" clearable />
            </el-form-item>
            <el-form-item label="-">
              <el-input placeholder="逾期天数最大值" v-model="dataForm.maxOverdueDays" style="width: 160px" maxlength="30" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="">
              <el-select placeholder="全部状态" v-model="dataForm.currentStatus" clearable>
                <el-option v-for="(item,key) of allStatus" :key="key" :label="item" :value="key" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin:10px 0 0 80px;">
          <el-col>
            <el-form-item>
              <el-button type="primary" @click="getList(1)">
                <fa-icon class="fa-search" />查询</el-button>
              <el-button type="primary" @click="batchCancel">
                批量撤回</el-button>
              <el-button type="primary" @click="batchAssign">
                批量分派</el-button>
              <el-button plain type="" @click="onReset">
                <fa-icon class="fa-refresh" />重置
              </el-button>
              <el-button type="" @click="importDialog = true">
                <fa-icon class="fa-upload" />导入
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-row class="table-top">
      <el-table :data="dataList" :border="true" v-loading="tableLoading" tooltip-effect="light" @selection-change="handleSelectionChange" @select-all="selectAllEvent" class="tc-table-box" size="small">
        <el-table-column type="selection" width="55" fixed="left"></el-table-column>
        <template v-for="(column, index) in REPAYMENT_HEAD_LIST">
          <el-table-column :prop="column.prop" :label="column.label" :key="index" :width="column.width" :show-overflow-tooltip="true" />
        </template>
        <el-table-column prop="operation" class-name="oper-col" label="操作" :width="180">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" plain @click="detailRow(scope.row)">详情</el-button>
            <el-button size="mini" type="primary" plain v-if="scope.row.followAcceptorName && scope.row.currentStatus !== 'REPAYED'" @click="cancelRow([scope.row.overdueId])">撤回</el-button>
            <el-button size="mini" type="primary" plain v-if="!scope.row.followAcceptorName && scope.row.currentStatus !== 'REPAYED'" @click="assignRow([scope.row.overdueId])">分派</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row class="pagination-top">
        <pagination :pageNum.sync="dataForm.pageNum" :curSizes.sync="dataForm.pageSize" :total="total" @getList="getList" />
      </el-row>
    </el-row>
    <!--分派-->
    <el-dialog title="分派" :visible.sync="assignDialog" width="40%" :close-on-click-modal="false">
      <assign-acceptor v-if="assignDialog" @uppdataSuccess="updataSuccess" @close="closeAssign" />
    </el-dialog>
    <!--详情-->
    <el-dialog :title="editData.customerName" :visible.sync="detailDialog" width="90%" :close-on-click-modal="false">
      <repayment-detail v-if="detailDialog" :overdata="editData" @close="closeDetails" />
    </el-dialog>
    <!-- 文件导入 -->
    <el-dialog :visible.sync="importDialog" width="80%" custom-class="import-dialog" :close-on-click-modal="false">
      <import-file v-if="importDialog" @updateData="uppdataSuccess('import')"></import-file>
    </el-dialog>
  </div>
</template>

<script>
import OrganizationCascader from '@/components/organizationCascader'
import { CURRENT_STATUS, REPAYMENT_HEAD_LIST } from '../js/contant.js'
import AssignAcceptor from './AssignAcceptor'
import RepaymentDetail from './RepaymentDetail'
import api from '../api'
import { CONSTANT_OBJ } from '@/utils/constant'
import { common } from '@/utils/common'
import { mapState } from 'vuex'
import ImportFile from './importFile'
import {
  encryptName
} from '@/utils/util'
export default {
  components: { AssignAcceptor, RepaymentDetail, ImportFile, OrganizationCascader },
  data () {
    return {
      CURRENT_STATUS,
      REPAYMENT_HEAD_LIST,
      tableLoading: false,
      assignDialog: false,
      detailDialog: false,
      importDialog: false,
      editData: {},
      dataForm: {
        freeCondition: '',
        acceptorName: '',
        currentStatus: '',
        minOverdueDays: '',
        maxOverdueDays: '',
        acceptorOrgNo: '',
        followAcceptorName: '',
        followAcceptorOrgNo: '',
        productNoList: [],
        pageNum: 0,
        pageSize: 10
      },
      total: 0,
      dataList: [],
      slectedList: [],
      assignOverdueIds: [],
      selectedIds: [],
      allStatus: {}
    }
  },
  mounted () {
    this.$store.dispatch('common/queryProductData', { pageNum: 0, pageSize: 99 })
    this.allStatus = {
      // ...this.dicts['repay_current_status'].childMap,
      ...this.dicts['repay_follow_status'].childMap
    }
    console.log(this.allStatus, '状态')
    this.getList()
  },
  methods: {
    // 查询列表
    getList (val) {
      if (!this.checkDate()) return
      this.dataForm.pageNum = val || this.dataForm.pageNum
      this.tableLoading = true
      api.postQueryOverdueData(this.dataForm).then(res => {
        const { responseCode, data } = res
        if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
          this.dataList = data.list || []
          this.dataList.forEach(item => {
            item.newStatus = this.allStatus[item.currentStatus]
            item.newProduct = this.dicts['product_type'].childMap[item.productType]
            item.newCusName = encryptName(item.customerName)
            item.newAddr = `${item.organCity}-${item.organTown}`
          })
          this.total = parseInt(data.total) || 0
        }
      }).finally(() => {
        this.tableLoading = false
      })
    },
    // 选中
    handleSelectionChange (val) {
      this.slectedList = val
      this.selectedIds = []
      this.slectedList.forEach(item => {
        this.selectedIds.push(item.overdueId)
      })
    },
    // 批量撤回
    batchCancel () {
      if (!this.checkoutData('PROCESSING')) {
        return false
      }
      this.cancelRow(this.selectedIds)
    },
    // 撤回
    cancelRow (overdueIds) {
      console.log(overdueIds)
      common.confirmFn('撤回后您可重新进行分派', '是否确定撤回此分派').then(res => {
        if (res) {
          api.postRepayCancelData({overdueIds}).then(res => {
            this.successFn(res)
          })
        }
      })
    },
    // 分派
    assignRow (overdueIds) {
      console.log(overdueIds, '分派id')
      this.assignDialog = true
      this.assignOverdueIds = [...overdueIds]
    },
    // 批量分派
    batchAssign () {
      if (!this.checkoutData('WAIT_ASSIGN')) {
        return false
      }
      this.assignRow(this.selectedIds)
    },
    // 校验数据
    checkoutData (val) {
      let result = true
      let data = [...this.slectedList]
      if (data.length === 0) {
        this.$message({
          message: '请选择待撤回案件',
          type: 'warning'
        })
        result = false
      }
      let allData = data.every((item) => (item.currentStatus === val))
      if (!allData) {
        this.$message({
          message: '请正确选择待撤回案件',
          type: 'warning'
        })
        result = false
      }
      return result
    },
    updataSuccess (acceptor) {
      let data = {
        followAcceptorName: acceptor.realName,
        followAcceptorNo: acceptor.userName,
        followAcceptorOrgName: acceptor.organizationName,
        followAcceptorOrgNo: acceptor.organizationCode,
        overdueIds: this.assignOverdueIds
      }
      api.postAssignAcceptorsData(data).then(res => {
        this.successFn(res, 'assignDialog')
      })
    },
    uppdataSuccess (dialogName) {
      this.getList(0)
      // this.dialog[`${dialogName}Dialog`] = false
      this.importDialog = false
    },
    successFn (res, dialog) {
      const { responseCode, responseMsg: message } = res
      if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
        this.$message({
          message,
          type: 'success'
        })
        if (dialog) {
          this[dialog] = false
        }
        this.getList(1)
      }
    },
    // 获取详情
    detailRow (row) {
      this.editData = { ...row }
      this.detailDialog = true
    },
    closeDetails (val) {
      this.detailDialog = val
    },
    selectAllEvent (selection) {
      this.slectedList = [...selection]
    },
    onReset () {
      let obj = {}
      for (let index in this.dataForm) {
        if (index === 'productNoList') {
          obj[index] = []
        } else {
          obj[index] = ''
        }
      }
      obj.pageNum = 1
      obj.pageSize = 10
      this.dataForm = {...obj}
      this.getList(1)
    },
    closeAssign () {
      this.assignDialog = false
    },
    checkDate () {
      let { minOverdueDays, maxOverdueDays } = this.dataForm
      let minNum = Number(minOverdueDays)
      let maxNum = Number(maxOverdueDays)
      if (isNaN(minNum) || isNaN(maxNum)) {
        this.$message({
          message: '请输入正确的逾期天数',
          type: 'warning'
        })
        return false
      }
      if (minNum > maxNum) {
        this.$message({
          message: '最小逾期天数不可大于最大天数',
          type: 'warning'
        })
        return false
      }
      if ((minOverdueDays && minNum <= 0) || (maxOverdueDays && maxNum <= 0)) {
        this.$message({
          message: '逾期天数只能输入大于0的数字',
          type: 'warning'
        })
        return false
      }
      return true
    }
  },
  computed: {
    ...mapState({
      products: state => state.common.products,
      dicts: state => state.common.dicts
    })
  }
}
</script>
<style lang="less">
@import '../../../assets/css/common.less';
// 表格外边框
.tc-table-box {
  border: 1px solid @main-border-color;
  border-bottom: none;
  width:100%;
}

.el-table thead{
  color: #707277;
}
.tc-table-box th{
  background-color: @panel-color !important;
}
</style>
